<template>
	<view>
		<uni-popup
			ref="dateselect"
			@maskClick="closePopup()"
			catchtouchmove="true"
		>
			<view class="popup-bd">
				<view class="popup-title">
					选择周期
					<uni-icons
						type="closeempty"
						size="50rpx"
						color="#666666"
						class="popup-close"
						@click="closePopup()"
					></uni-icons>
				</view>
				<view class="popup-content">
					<view class="tc lh80 f36 b">{{ nowYear }}年</view>
					<view class="tab-line1">
						<scroll-view
							scroll-x="true"
							:scroll-into-view="scrollIndex"
							scroll-with-animation="true"
							class="tab-bar1"
						>
							<view
								class="tab-item1"
								:class="
									item.value === activeMonth
										? 'tab-active'
										: ''
								"
								v-for="item in dataList"
								:key="item.value"
								:id="'scroll' + item.value"
								@click="changeMonth(item)"
							>
								<view class="f34 fwb lh60">{{
									item.name
								}}</view>
								<hr
									:class="{
										'tab-active-line':
											item.value == activeMonth,
									}"
									class="mt20"
								/>
							</view>
						</scroll-view>
					</view>
					<!-- 时间段 -->
					<view class="box-bd-cont mt20 df jsb fx-wp">
						<view
							class="item-box mb30"
							v-for="(item, index) in weekList"
							:key="index"
						>
							<view
								:class="{
									'time-active':
										item.startDate + '~' + item.endDate ===
										activeWeek,
								}"
								class="item-cont"
								@tap="changeWeek(item, index)"
							>
								<view class="f32 fwb g6b"
									>第{{ item.weekNum }}周</view
								>
								<view class="tag-color f24"
									>{{ item.beginTime }}至{{
										item.endTime
									}}</view
								>
							</view>
						</view>
					</view>
				</view>
				<view class="popup-bottom df ac"
					><button
						class="primary-button linear w90"
						@tap="submitChooseDate()"
					>
						确定
					</button></view
				>
			</view>
		</uni-popup>
	</view>
</template>

<script>
const dayjs = require('@/common/dayjs.min.js')
import {
	getCurrentDay,
	formatDate,
	getCurrentWeekRange,
} from '@/common/utils.js'
import { nextTick } from 'vue'
export default {
	name: 'select-month',
	emits: ['submit'],
	props: {
		value: {
			type: Array,
			value: [],
			default() {
				return []
			},
		},
		orderData: {
			type: Object,
			default: () => {
				return {}
			},
		},
		//往前几个月
		befor: {
			type: [Number, String],
			default: 6,
		},
		//往后几个月
		after: {
			type: [Number, String],
			default: 6,
		},
	},
	data() {
		return {
			dataList: [],
			activeMonth: '',
			weekList: [],
			activeWeek: '',
			scrollIndex: '',
			monthBefor: 6,
			monthAfter: 6,
			nowYear: '',
		}
	},
	methods: {
		init() {
			this.initData()
			this.$refs.dateselect.open('bottom')
		},
		changeMonth(item) {
			this.nowYear = item.year
			this.activeMonth = item.value
			this.scrollIndex = 'scroll' + item.value
			this.weekList = this.weeks(this.activeMonth)
		},
		changeWeek(item, index) {
			this.activeWeek = item.startDate + '~' + item.endDate
		},
		//根据月份获取天数和对应的星期
		monthDays() {
			let _that = this
			let dateObj = new Date()
			let startMonth = new Date()
			let endMonth = new Date()
			let nowYear = dateObj.getFullYear()
			let nowMonth = dateObj.getMonth()
			this.nowYear = nowYear
			startMonth.setMonth(nowMonth - this.monthBefor)
			endMonth.setMonth(nowMonth + this.monthAfter)
			let dataList = []
			while (endMonth.getTime() - startMonth.getTime() >= 0) {
				let year = startMonth.getFullYear()
				let month =
					(startMonth.getMonth() + 1).toString().length === 1
						? '0' + (startMonth.getMonth() + 1)
						: startMonth.getMonth() + 1
				dataList.push({
					year: year,
					name: `${month}月`,
					value: `${year}-${month}`,
				})
				startMonth.setMonth(startMonth.getMonth() + 1)
			}
			this.activeMonth =
				this.value[0] ||
				nowYear +
					'-' +
					(nowMonth + 1 > 9 ? nowMonth + 1 : '0' + (nowMonth + 1))
			this.dataList = dataList
			this.weekList = this.weeks(this.activeMonth)
		},
		//获取当前所在周的时间
		getCurrentWeek() {
			let dateObj = new Date()
			const { currentWeekStartDay, currentWeekLastDay } =
				getCurrentWeekRange(dayjs())
			this.activeWeek =
				this.value[1] || currentWeekStartDay + '~' + currentWeekLastDay
		},
		//关闭弹窗
		closePopup() {
			this.$refs.dateselect.close()
		},
		//根据月份查询周
		weeks(now_month) {
			let { time } = this
			let week_array = []
			let today = new Date(Date.parse(now_month))
			let year = today.getFullYear()
			let month = today.getMonth()
			let i = 0
			let start = new Date(year, month, 1) // 得到当月第一天
			let end = new Date(year, month + 1, 0) // 得到当月最后一天

			// 循环每周最后天叠设置为第一天，直到最后一天小于当月的最后一天
			let weekNum = 1
			while (start <= end) {
				const monday = new Date(start.getTime())
				const sunday = new Date(start.getTime())
				let startDate, endDate

				monday.setDate(monday.getDate() + 1 - monday.getDay())
				sunday.setDate(sunday.getDate() + 7 - sunday.getDay())
				startDate = formatDate(monday, 'yyyy-MM-dd')
				endDate = formatDate(sunday, 'yyyy-MM-dd')
				if (
					!(
						endDate.slice(5, 7) === startDate.slice(5, 7) &&
						end.getTime() == start.getTime()
					)
				) {
					week_array.push({
						startDate,
						endDate,
						beginTime: startDate.slice(5, 10).replace('-', '.'),
						endTime: endDate.slice(5, 10).replace('-', '.'),
						id: monday.getTime(),
						weekNum: weekNum,
					})
				}
				start = sunday
				weekNum += 1
			}
			return week_array
		},
		//确认选择
		submitChooseDate() {
			this.closePopup()
			this.$emit('submit', [this.activeMonth, this.activeWeek])
		},
		//初始化数据
		initData() {
			this.monthBefor = parseInt(this.befor)
			this.monthAfter = parseInt(this.after)
			this.monthDays()
			this.getCurrentWeek()
			this.scrollIndex = ''
			this.$nextTick(() => {
				this.scrollIndex = 'scroll' + this.activeMonth
			})
		},
	},
}
</script>

<style scoped lang="scss">
.tab-line1 {
	height: 76rpx;
	line-height: 70rpx;
	overflow: hidden;
	width: 100%;
}
.tab-bar1 {
	width: 100%;
	box-sizing: content-box;
	height: 70rpx;
	position: relative;
	background-color: #ffffff;
	overflow-x: auto;
	overflow-y: hidden;
	-webkit-overflow-scrolling: touch;
	user-select: none;
	padding-bottom: 30rpx;
	white-space: nowrap;
}
.tab-item1 {
	display: inline-block;
	position: relative;
	text-align: center;
	font-size: 36rpx;
	margin: 0 20rpx;
}
.tab-active {
	color: #409eff;
}
.item-box {
	width: 48%;
	height: 170rpx;
}
.item-cont {
	height: 124rpx;
	font-size: 32rpx;
	border: 2rpx solid $tag-color;
	text-align: center;
	border-radius: 10rpx;
	padding-top: 46rpx;
}
.box-bd-cont {
	background-color: #ffffff;
	width: 100%;
	height: calc(100vh - 580rpx);
	overflow-y: auto;
	align-content: flex-start;
}
.time-active {
	border-color: $active-color;
	background: #f1f8ff;
	color: $active-color;
	.g6b {
		color: $active-color;
	}
	.tag-color {
		color: $active-color;
	}
}
.time-disabled {
	background-color: #fafafa;
	color: #999999;
}
.tab-active-line {
	width: 100%;
	height: 6rpx;
	background-color: $primary-color;
	color: $primary-color;
}
.tab-active {
	font-weight: 900;
}
.popup-title {
	background: linear-gradient(90deg, #e3edff 0%, rgba(223, 234, 255, 0) 100%);
}
</style>
